package com.netty.netty.high.demo2;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LoggingHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class NettyClient {

  private static final Logger log= LoggerFactory.getLogger(NettyClient.class);

  public static void main(String[] args) {

    //采用短连接解决“”粘包“”问题，无法解决半包问题
    for (int i = 0; i < 10; i++) {
      sendMessage("hello");
    }


  }


  public static void sendMessage(String msg){

     NioEventLoopGroup eventLoopGroup = new NioEventLoopGroup();
     ChannelFuture channelFuture = new Bootstrap()
            .group(eventLoopGroup)
            .channel(NioSocketChannel.class)
            .handler(new ChannelInitializer<Channel>() {
              @Override
              protected void initChannel(Channel ch) throws Exception {

                //不进行加解密不然展示不出粘包效果
//                ch.pipeline().addLast(new StringEncoder());
                ch.pipeline().addLast(new LoggingHandler());

                ch.pipeline().addLast(new ChannelInboundHandlerAdapter(){
                  @Override
                  public void channelActive(ChannelHandlerContext ctx) throws Exception {
                    ByteBuf buffer = ctx.alloc().buffer(16);
                    buffer.writeBytes(msg.getBytes("utf-8"));
                    ch.writeAndFlush(buffer);
                    ch.close();
                    ChannelFuture closeFuture = ch.closeFuture();
                    closeFuture.addListener(new ChannelFutureListener() {
                      @Override
                      public void operationComplete(ChannelFuture future) throws Exception {
                        eventLoopGroup.shutdownGracefully();
                      }
                    });
                  }
                });

              }
            }).connect("localhost", 8080);


  }

}
